import { configTemplateType } from "../type";

/**
 * 发送指定的消息
 */
export async function xhsSendMessage(config: configTemplateType) {
  let inputNode = document.querySelector(".d-textarea textarea") as HTMLElement;
  console.log(inputNode, "inputNode");
  inputNode.click();

  if (config.commentText) {
    insertTextWithCommand(inputNode, config.commentText);
  } else {
    let index = config.serialNum - 1;
    await sleep(1000);
    let contentNodes = document.querySelectorAll(
      ".comment-list-desc"
    ) as unknown as HTMLElement[];
    console.log(contentNodes, "contentNodes");

    contentNodes[index].click();
  }

  // 点击发布评论
  let submitNode = document.querySelector(
    ".comment-input button"
  ) as HTMLElement;
  submitNode.click();
}

export function insertTextWithCommand(textarea: any, text: any) {
  textarea.focus();
  // 使用document.execCommand（兼容老浏览器）
  document.execCommand("insertText", false, text);
}

/**
 * 弹出讲解商品的方法
 */
export async function xhsPopUpGoodsPop(config: configTemplateType) {
  let index = config.serialNum - 1;
  let goodsNodes = document.querySelectorAll(".rowCommon");
  console.log(goodsNodes, "goodsNodes");

  // 商品的index
  let goodsBtnNodes = goodsNodes[index].querySelectorAll(
    ".operation-item"
  ) as unknown as HTMLElement[];
  console.log(goodsBtnNodes, "goodsNodes");
  // 商品中要操作按钮的index
  let btnIndex = 2;
  // console.log(goodsBtnNodes, "goodsBtnNodes");
  let btnText = goodsBtnNodes[btnIndex].innerText;
  if (btnText == "结束讲解") {
    goodsBtnNodes[btnIndex].click();
  }
  await setExplanation(goodsBtnNodes, btnIndex, 0);
}

/**
 * 设置当前正在讲解的商品
 */
export async function setExplanation(
  goodsBtnNodes: any,
  btnIndex: number,
  num: number
) {
  let btnText1 = goodsBtnNodes[btnIndex].innerText;
  if (btnText1 == "讲解") {
    goodsBtnNodes[btnIndex].click();
  } else if (num < 50) {
    console.log("traverse循环次数：", num);
    await sleep(100);
    setExplanation(goodsBtnNodes, btnIndex, num + 1);
  }
}

/**
 * 延迟后续逻辑的执行时间
 */
export function sleep(time: number | undefined) {
  return new Promise<void>((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
}
